<?php
//欢乐钓鱼
namespace App\Http\Controllers\Api\Hldy;

use App\Http\Controllers\Controller;
use App\Models\Hldy\FishLog;
use App\Models\Hldy\PayLog;
use App\Models\Hldy\UserInfo;
use App\Tools\Hldy\Fish;
use App\User;
use App\UserCoinLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DyController extends Controller
{
    protected $wechat;

    private $reward_count = 2;

    public function __construct()
    {
        $this->wechat = app('wechat');
    }

    /**
     * 接口访问前检查用户信息是否存在
     */
    protected function _checkUser() {
        $user = auth()->user();

        $userInfo = UserInfo::findByUserId($user->id);
        if(empty($userInfo->id)) {
            //初始化用户信息数据
            $now = time();
            $userInfoModel = new UserInfo();
            $userInfoModel->user_id = $user->id;
            $userInfoModel->add_time = $now;
            $userInfoModel->save();
        }
    }

    /**
     * 获取用户信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $this->_checkUser();
        $user = auth()->user();

        $userInfo = UserInfo::findByUserId($user->id);

        $total = UserCoinLog::totalXyb( $user->id );
        $XYB = $total < 0 ? 0 : $total  ;

        $data = [
            'gold' => $XYB,               /*用户金币*/
            'nickname' => $user->nickname,           /*用户昵称*/
            'pic' => $user->avatar,                  /*用户头像*/
            'luckynum' => $userInfo->lucky_num,       /*幸运值，钓鱼失败时候增加幸运值*/
            'totalget' => $userInfo->total_get_gold, /*总收获*/
            'totalplay' => $userInfo->total_play,    /*下杆数*/
            'sr' => $userInfo->hit_rate,             /*成功率*/
        ];
        return response()->json([
            'code'  => 0,
            'msg'   => 'success',
            'data'  => $data,
        ]);
    }

    /**
     * 钓鱼
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function doFish( Request $request )
    {
        $this->_checkUser();
        $currentUser = auth()->user();

        $goldNum = abs( (int)$request->input('goldnum') );

        //获取实时数据
        $user = User::find($currentUser->id);

        if(!Fish::checkGoldIsValid($goldNum)) {
            return response()->json([
                'code' => 1,
                'msg'  => '下杆金额错误',
                'data' => [],
                'balance' => $user->XYB,
            ]);
        }

        if($user->XYB < $goldNum) {
            return response()->json([
                'code' => 1,
                'msg'  => '用户余额不足',
                'data' => [],
                'balance' => $user->XYB,
                ]);
        }

        //0:成功 1:失败 -1:未登录
        $code = 0;
        $msg  = 'success';
        $totalGold = 0;

        //钓到条数
        $hitNum = Fish::getHitNum($goldNum);

        //钓到数据
        $data = [
            'fish' => [],
        ];

        try {
            DB::beginTransaction();

            $now = time();

            $key = $user->id . '-' . $now;

            //记录放钓记录
            $fishLogModel = new FishLog();
            $fishLogModel->user_id = $user->id;
            $fishLogModel->gold = $goldNum;
            $fishLogModel->hit = 0;             //是否钓中
            $fishLogModel->hit_num = 0;          //钓中条数
            $fishLogModel->add_time = $now;
            $fishLogModel->update_time = 0;
            $fishLogModel->key = $key;
            $fishLogModel->save();
            $fishLogId = $fishLogModel->id;

            //查询上一次钓鱼时间
            $preFishLogItemArr = FishLog::where('id', '<', $fishLogId)->where('user_id', $user->id)->orderBy('id', 'desc')->limit(1)->get()->toArray();
            if(!empty($preFishLogItemArr[0])) {
                if($now - $preFishLogItemArr[0]['add_time'] < config('hldy.time_limit')) {  //上一次下杆时间比下杆停顿时间短，认为并发
                    throw new \Exception("请勿重复出杆", 1);
                }
            }

            //扣款前记录扣款日志
            $payLogModel = new PayLog();
            $payLogModel->user_id = $user->id;
            $payLogModel->from_XYB = $user->XYB;
            $payLogModel->add_XYB = -$goldNum;
            $payLogModel->to_XYB = $user->XYB - $goldNum;
            $payLogModel->add_time = $now;
            $payLogModel->update_time = $now;
            $payLogModel->save();

            //更新用户余额信息
            //当次钓鱼扣款
            // User::where('id', $user->id)->where('XYB', '>=', $goldNum)->where('XYB', $user->XYB)->update(['XYB'=>DB::raw('XYB-' . $goldNum)]);

            $key = '2-'. $user->id . '-' . -$goldNum . '-' . $now;

            UserCoinLog::log( 2, $user->id, UserCoinLog::TYPE_XYB, -$goldNum, '钓鱼消耗', $key );

            //钓到，取鱼，计算并更新奖励和用户信息
            $hitTimes  = 0;
            if($hitNum > 0) {
                $hitTimes = 1;

                //扣款成功，更新放钓记录
                $fishLogModel->hit = 1;
                $fishLogModel->hit_num = $hitNum;
                $fishLogModel->update_time = $now;
                $fishLogModel->save();

                //获取鱼
                $takeFishInfo = Fish::takeFish($hitNum, $goldNum);
                $totalGold = $takeFishInfo['totalGold'];
                $data['fish'] = $takeFishInfo['fishList'];

                //记录钓中奖励记录
                //获取新的用户信息
                $user = User::find($user->id);
                $payLogModel = new PayLog();
                $payLogModel->user_id    = $user->id;
                $payLogModel->from_XYB    = $user->XYB;
                $payLogModel->add_XYB     = $totalGold;
                $payLogModel->to_XYB      = $user->XYB + $totalGold;
                $payLogModel->add_time = $now;
                $payLogModel->update_time = $now;
                $payLogModel->save();


                //钓到的鱼增加余额
                // User::where('id', $user->id)->where('XYB', $user->XYB)->update(['XYB'=>DB::raw('XYB+' . $totalGold)]);

                $key = '2-'. $user->id . '-' . $totalGold . '-' . $now;
                UserCoinLog::log( 2, $user->id, UserCoinLog::TYPE_XYB, $totalGold, '钓鱼获得', $key );

                $this->rewardFinder($user, $totalGold);

            }

            //更新用户汇总信息
            $userInfoModel = UserInfo::findByUserId($user->id);
            $userInfoModel->total_get_gold += $totalGold;
            $userInfoModel->total_play += 1;
            $userInfoModel->hit_times += $hitTimes;
            $userInfoModel->hit_rate = $userInfoModel->hit_times / $userInfoModel->total_play;
            $userInfoModel->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            $code = 1;
            $msg = $e->getMessage();
        }

        //获取用户最新信息（余额）
        $user = User::find($user->id);
        return response()->json([
            'code'  => $code,
            'msg'   => $msg,
            'data'  => $data,
            'totalGold' => $totalGold,
            'fishNum' => $hitNum,
            'balance' => $user->XYB,
        ]);
    }

    /**
     * 奖励上级
     */
    public function rewardFinder($user, $total)
    {
        if ($this->reward_count) {
            if ($finder = User::where('id', $user->finder_id)->first()) {
                if (floatval($xyb = bcmul($total, 0.05, 2))) {
                    try {
                        $tmp_xyb = $xyb * 100;
                        $this->wechat->staff->message('恭喜您获得' . $tmp_xyb . '个小妖币的推荐奖励。')->to($finder->openid)->send();
                    } catch (\Exception $e) {
                    }
                    // $finder->XYB += $xyb;
                    // $finder->save();

                    $key = '2-'. $finder->id . '-' . $xyb . '-' . time() . '-1';
                    UserCoinLog::log( 2, $finder->id, UserCoinLog::TYPE_XYB, $xyb, '推荐奖励', $key );

                    $this->reward_count--;
                    $this->rewardFinder($finder, $total);
                }
            }
        }
    }
}
